#import "MyDocumentController.h"
#import "WTDocument.h"

@implementation MyDocumentController
- (id)init
{
    self = [super init];
    if (self) {
		if(![[NSUserDefaults standardUserDefaults] objectForKey:@"WTFirstRunPanther"]) {
			[self createUserDafaults];
		}
		//
		[self checkWTVerison:nil];
    }
    return self;
}

- (void) createUserDafaults {
	[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"WTFirstRunPanther"];
	[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"WTShowStartupWindow"];
	[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WTRecordingMode"];
	NSString *localVersionString = [[[NSBundle bundleForClass:[self class]] infoDictionary] objectForKey:@"CFBundleVersion"];
	NSNumber *localVersionNumber = [NSNumber numberWithDouble:[localVersionString doubleValue]];
	[[NSUserDefaults standardUserDefaults] setObject:localVersionNumber forKey:@"WTHasRejectVersion"];
	NSRunAlertPanel(NSLocalizedString(@"Welcome user",
				@"Greetings for new user of worktimer."),
				NSLocalizedString(@"Thanks for using my little timetracking application. Good luck. Gersh",
				@"Greeting text for new user of worktimer."),
				NSLocalizedString(@"OK", @"OK"), nil, nil);
}

- (void)notifyClose:(id)sender {
	[self updateRecentDocs:nil];
	//NSLog(@"notifyClose: %i", [[self documents] count]);
	if ([[self documents] count] <= 1) 
		[startWindow makeKeyAndOrderFront:nil];
	else 
		[startWindow close];
}

- (void)notifyOpen:(id)sender {
	[self updateRecentDocs:nil];
	//NSLog(@"notifyOpen: %i", [[self documents] count]);
	[startWindow close];
	}

- (void)noteNewRecentDocument:(NSDocument *)aDocument {
	[self updateRecentDocs:nil];
	[super noteNewRecentDocument:(NSDocument *)aDocument];
}

- (IBAction) checkWTVerison:(id)sender {
    [NSThread detachNewThreadSelector: @selector(checkVersionInThread:) toTarget: self withObject: sender];
}

- (void) checkVersionInThread: (id) sender {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSString *localVersionString = [[[NSBundle bundleForClass:[self class]] infoDictionary] objectForKey:@"CFBundleVersion"];
	NSNumber *localVersionNumber = [NSNumber numberWithDouble:[localVersionString doubleValue]];
    
	NSDictionary *productVersionDict = [NSDictionary dictionaryWithContentsOfURL: [NSURL URLWithString:@"http://www.gersh.no/cocoa/worktimer.plist"]];
    if (productVersionDict != nil) {
		NSNumber *latestVersionNumber = [productVersionDict valueForKey:@"WTLatestVersion"];
		NSLog(@"latestVersionNumber: %@", latestVersionNumber);
		NSNumber *hasRejectVersionNumber =[[NSUserDefaults standardUserDefaults] objectForKey:@"WTHasRejectVersion"];
		NSLog(@"hasRejectVersionNumber: %@", hasRejectVersionNumber);
        if([localVersionNumber floatValue] < [latestVersionNumber floatValue] && [hasRejectVersionNumber floatValue] != [latestVersionNumber floatValue]) {
			int button = NSRunAlertPanel([productVersionDict valueForKey:@"WTUpdateHead"], [productVersionDict valueForKey:@"WTUpdateMessage"], @"OK",@"Cancel", @"Don't Remind Me Again",  nil);
			NSLog(@"button: %i", button);
			if(button == 1) [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[productVersionDict valueForKey:@"WTDownloadURL"]]];
			else if (button == -1) {
				[[NSUserDefaults standardUserDefaults] setObject:latestVersionNumber forKey:@"WTHasRejectVersion"];
			}
		}
    } else {
   NSLog(@"Unable to download version information.");
    }
    [pool release];
    [NSThread exit];
}

- (void)dealloc {
    [super dealloc];
}

- (void)awakeFromNib {
	[self updateRecentDocs:nil];
}

- (IBAction)updateRecentDocs:(id)sender {
	myRecentDocs = [[self recentDocumentURLs] copy];
	NSArray *matrixCells = [recentDocMatrix cells];
	unsigned i, count = [matrixCells count];
	id matrixItem, recentDocItem;
	
	for (i = 0; i < count; i++) {
		matrixItem = [matrixCells objectAtIndex:i];
		[matrixItem setTransparent:YES];
		if(i < [myRecentDocs count]) {
			recentDocItem = [myRecentDocs objectAtIndex:i];
			[matrixItem setTitle:[[[recentDocItem path] lastPathComponent] stringByDeletingPathExtension]];
			[matrixItem setTransparent:NO];
		}
	}
}

- (IBAction)openRecent:(id)sender {
	[self openDocumentWithContentsOfURL:(NSURL *)[myRecentDocs objectAtIndex:[sender selectedTag]] display:(BOOL)YES error:(NSError **)nil];
}

- (IBAction)goToGersh:(id)sender
{
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:NSLocalizedString(@"http://www.gersh.no", @"")]];
}

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
	return NO;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
		if([[NSUserDefaults standardUserDefaults] integerForKey:@"WTShowStartupWindow"] > 0) [startWindow makeKeyAndOrderFront:nil];
		//NSLog(@"applicationDidFinishLaunching: ");
}


@end

/*
- (IBAction)exportData:(id)sender {
	//[[self currentDocument]  startExportSheet:nil];
}
- (IBAction)feedBack:(id)sender {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"mailto:mailaddress?subject=WorkTimer%201.1%20Feedback"]];
}

- (IBAction)printMyDocument:(id)sender {
	//[[self currentDocument] startExportSheet:nil];
}*/
